package jmine.tec.web.wicket.component.table.dataprovider;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import jmine.tec.report.api.table.ReportRow;
import jmine.tec.report.api.table.ReportTable;
import jmine.tec.report.impl.table.TableRowIterator;
import jmine.tec.web.wicket.model.DefaultDetachableModel;

import org.apache.wicket.markup.repeater.data.IDataProvider;
import org.apache.wicket.model.IModel;

/**
 * {@link IDataProvider} que converte os dados retornados pelo {@link IDataProvider} "delegate" em {@link ReportRow}
 * 
 * @author Rafael Volpato
 * @date Aug 8, 2011
 * @param <S> Tipo do {@link IDataProvider} origem
 */
public class DataProviderConverter<S> implements IDataProvider<ReportRow> {

    private final IDataProvider<S> delegate;

    private final ReportTable<?> table;

    /**
     * Construtor.
     * 
     * @param delegate {@link IDataProvider}
     * @param table {@link ReportTable}
     */
    public DataProviderConverter(IDataProvider<S> delegate, ReportTable<?> table) {
        this.delegate = delegate;
        this.table = table;
    }

    /**
     * {@inheritDoc}
     */
    public void detach() {
        this.delegate.detach();
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public Iterator<ReportRow> iterator(int first, int count) {
        List<?> columns = this.table.getColumns();
        if (columns.isEmpty()) {
            List<ReportRow> emp = Collections.emptyList();
            return emp.iterator();
        } else {
            return new TableRowIterator(this.delegate.iterator(first, count), columns, this.table.getTableGroup());
        }
    }

    /**
     * {@inheritDoc}
     */
    public int size() {
        List<?> columns = this.table.getColumns();
        if (columns.isEmpty()) {
            return 0;
        } else {
            return this.delegate.size();
        }
    }

    /**
     * {@inheritDoc}
     */
    public IModel<ReportRow> model(ReportRow object) {
        return new DefaultDetachableModel<ReportRow>(object);
    }
}
